//
//  CustomTimerStore.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/11/15.
//

import Foundation
import CoreData

let kCustomTimer = "CustomTimer"

class CustomTimerStore {
    
    /// 保存或修改计时器
    /// - Parameter timer: XCCustomTimer
    static func save(timer: XCCustomTimer) {
        let managedContext = CoreDataStack.shared.managedContext
        
        if let t = find(uuid: timer.uuid) { // 有，改
            t.name = timer.name
            t.type = Int32(timer.type?.id ?? 0)
            t.startTime = timer.startTime ?? 0
            t.endTime = timer.endTime ?? 0
            
            t.bell = timer.bell
            t.duration = timer.duration ?? 0
            t.color = timer.color
            t.lastUpdate = FNowTime()
            if t.createTime == 0 {
                t.createTime = FNowTime()
            }
        } else {
            let t = NSEntityDescription.insertNewObject(forEntityName: kCustomTimer, into: managedContext) as! CustomTimer
            t.uuid = timer.uuid
            t.name = timer.name
            t.type = Int32(timer.type?.id ?? 0)
            t.startTime = timer.startTime ?? 0
            t.endTime = timer.endTime ?? 0
            
            t.bell = timer.bell
            t.duration = timer.duration ?? 0
            t.color = timer.color
            t.createTime = FNowTime()
            t.lastUpdate = FNowTime()
        }
        
        do {
            try managedContext.save()
            print("保存或修改成功")
        } catch {
            print("操作失败：\(error)")
        }
    }
    
    static func query() -> NSFetchedResultsController<CustomTimer> {
        let managedContext = CoreDataStack.shared.managedContext

        let fetchRequest = NSFetchRequest<CustomTimer>(entityName: kCustomTimer)
        let predicate = NSPredicate(value: true)
        fetchRequest.predicate = predicate
        
        let sortDesc = NSSortDescriptor(key: "sort", ascending: false)
        let createTimeDesc = NSSortDescriptor(key: "createTime", ascending: false)
        fetchRequest.sortDescriptors = [sortDesc, createTimeDesc]
        
        let fetchedRC = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedContext, sectionNameKeyPath: nil, cacheName: nil)
        
        do {
            try fetchedRC.performFetch()
        } catch let error as NSError {
            print("Error: \(error.userInfo)")
        }

        return fetchedRC
    }
    
    static func find(uuid: String?) -> CustomTimer? {
        guard let uuid = uuid else { return nil }
        
        let managedContext = CoreDataStack.shared.managedContext
        let fetchRequest = NSFetchRequest<CustomTimer>(entityName: kCustomTimer)
        let predicate = NSPredicate(format: "uuid == %@", uuid) // 设置查询条件
        fetchRequest.predicate = predicate

        do {
            let fetchedObjects = try managedContext.fetch(fetchRequest)
            return fetchedObjects.first
        } catch {
            print("错误：\(error)")
        }
        
        return nil
    }
}
 
